package dyyx;
import java.util.Date;

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;

public abstract class JacksonUtil {
	
    private static final ObjectMapper mapper = new ObjectMapper();
    private static final String DATE_TIME_FORMAT = "yyyy-MM-dd HH:mm:ss";
    
    static{
    	// ALWAYS null 字段也会输出
    	// mapper.setSerializationInclusion(JsonInclude.Include.ALWAYS);
    	// 不输出 null 字段
    	mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
    	
    	mapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
    	mapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, true);

    	
    	// TODO 线程安全问题
    	// public class SimpleDateFormat extends DateFormat
    	// mapper.setDateFormat(new SimpleDateFormat(DATE_TIME_FORMAT,Locale.US));
    	
    	mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);

    	
    }

	

	public static void main(String[] args) throws Exception {
		System.out.println("hello,JacksonUtil,"+new Date());
		
		
		
	}
	
	
	public static final ObjectMapper getObjectMapper() {
		return mapper;
	}
	
	public static String toString(Object obj,boolean pretty) throws JsonProcessingException{
		if(obj==null){
			return null;
		}
		if(obj instanceof String){
			return (String)obj;
		}
		
		if(pretty){
			return mapper.writerWithDefaultPrettyPrinter().writeValueAsString(obj);
		}
		
		
		return mapper.writeValueAsString(obj);
	}
	
	public static <T> T toObject(String str,Class<T> clazz)throws JsonProcessingException, JsonMappingException{
		if(str==null){
			return null;
		}
		if(clazz.equals(String.class)){
			return (T)str;
		}
		
		return mapper.readValue(str, clazz);
	}
	
	
    public static <T> T toObject(String str, TypeReference<T> valueTypeRef)throws Exception{
    	if(str==null){
			return null;
		}
		return mapper.readValue(str, valueTypeRef);

    }

	
	
	
	
}
